# -*- coding: utf-8 -*-

"""
这里的 api 是前端 webbt 库使用的api.
"""

import json
import time

import uuid
from django.urls import reverse
from urlobject import URLObject
from cent import Client as CentClient, CentException, generate_token
from rest_framework import status
from rest_framework.response import Response
from rest_framework.exceptions import ParseError, ValidationError

import logging
logger = logging.getLogger('bt_server')

from app.models import BtResource
from base.settings import WEBSOCKET_SERVER_URL, WEBSOCKET_SECRET, WEBSOCKET_SERVER_TIME_OUT, WEBSOCKET_CHANNLE, WEBSOCKET_CLIENT_URL, WEBBT_RTC_CONFIG
from common.base_resful_view import BaseResfulView, QueryParameterNotPresentError

cent_client = CentClient(WEBSOCKET_SERVER_URL, WEBSOCKET_SECRET,
                         WEBSOCKET_SERVER_TIME_OUT)


class WebbtConfigerView(BaseResfulView):
    def get(self, request, *args, **kwargs):
        """获取webbt库所需配置信息"""

        timestamp = str(int(time.time()))
        user = '{}{}'.format(timestamp[-8:len(timestamp)], uuid.uuid4().hex[0:32])
        info = json.dumps({'client': 'browser', 'name': 'webbt'})
        token = generate_token(WEBSOCKET_SECRET, user, timestamp, info=info)

        request_url = request.get_raw_uri()

        return Response(
            {
                'data': {
                    'peerId': user,
                    'wsConfig': {
                        'user': user,
                        'url': WEBSOCKET_CLIENT_URL,
                        'timestamp': timestamp,
                        'token': token,
                        'info': info,
                        'channel': WEBSOCKET_CHANNLE
                    },
                    'rtcConfig': WEBBT_RTC_CONFIG,
                }
            },
            status=status.HTTP_200_OK)
